// 对用户进行描述和组织

#pragma once

#include <iostream>
#include <sys/socket.h>
#include <list>
#include <vector>

#include <string>

#include "Log.hpp"
#include "InetAddr.hpp"
#include"Lock.hpp"

using namespace LogMoudle;
using namespace InetAddrMoudle;
using namespace LockModule;

class UserInterface
{
public:
    virtual ~UserInterface() = default;
};



// 描述用户
class User : public UserInterface
{
private:
    InetAddr _id;

public:
    User(const InetAddr &id) : _id(id)
    {
    }

    void SendTo(int sockfd, const std::string &message)
    {

        LOG(Logevel::INFO) << " send message to " << _id.Ip() << " info: " << message;
        int n = sendto(sockfd, message.c_str(), message.size(), 0, _id.GetAddr(), _id.AddrLen());
        if (n <= 0)
        {
            LOG(Logevel::INFO) << " sned is false ";
        }
    }

    std::string ID()
    {
        return _id.Ip();
    }

     bool operator==(const InetAddr &u)
    {
        return _id == u;
    }

    ~User()
    {
    }
};

// 组织管理用户行为
class UserManger
{
private:
    std::list<User> _user;
    Mutex _mutex;
public:
    UserManger()
    {
    }
    void AddUser(InetAddr &_id)
    {
        LockGuard lock(_mutex);
        for (auto a : _user)
        {
            // 这里需要我们从新进行等号的运算符重载
            if (a == _id)
            {
                LOG(Logevel::INFO) << " 用户已经存在 ";
                return;
            }
        }
        LOG(Logevel::INFO) << " 新增用户: " << _id.Ip();
        _user.push_back(_id);
    }

    // 发送信息给用户
    void Router(int sockfd, const std::string &message)
    {
        LockGuard lock(_mutex);
        for (auto a : _user)
        {
            a.SendTo(sockfd, message);
        }
    }

    void PrintUser()
    {
        for (auto a : _user)
        {
            LOG(Logevel::INFO) << " 在线用户:----> " << a.ID();
        }
    }
};
